package com.health.widget;

import android.app.DatePickerDialog;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.DatePicker;
import android.widget.EditText;

import com.health.R;
import com.health.tools.GlobalConts;
import com.health.tools.ViewUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class EditTextWithDate2 extends EditText {
    private final static String TAG = "EditTextWithDate2";
    private Drawable dateIcon;
    private Context mContext;
    private Calendar c;
    private int mYear;
    private int mMonth;
    private int mDay;
    private boolean datePickerEnabled = true;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);

    private Date date;

    public EditTextWithDate2(Context context) {
        super(context);
        mContext = context;
        init();
    }

    public EditTextWithDate2(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init();
    }

    public EditTextWithDate2(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        init();
    }

    public Date getDate() {
        if (date == null) {
            if (TextUtils.isEmpty(getText().toString())) {
                // return new Date();
                return null;
            }
            try {
                Date d = format.parse(getText().toString());
                date = d;
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return date;
    }

    public void setDate(Date date) {
        if (date == null) {
            return;
        }
        this.date = date;
        String dateStr = format.format(date);
        String[] dates = dateStr.split("-");
        mYear = Integer.parseInt(dates[0]);
        mMonth = Integer.parseInt(dates[1]);
        mDay = Integer.parseInt(dates[1]);
        setText(dateStr);
    }

    private void init() {

        dateIcon = mContext.getResources().getDrawable(R.drawable.icon_calendar2);
        dateIcon.setBounds(0, 0,
                ViewUtils.dip2px(mContext,25),
                ViewUtils.dip2px(mContext,25));
        setCompoundDrawables(null, null, dateIcon, null);
        // setCompoundDrawablesWithIntrinsicBounds(null, null, dateIcon, null);
        c = Calendar.getInstance();
        final Calendar cal = Calendar.getInstance();
        mYear = cal.get(Calendar.YEAR); // 获取当前年份
        mMonth = cal.get(Calendar.MONTH);// 获取当前月份
        mDay = cal.get(Calendar.DAY_OF_MONTH);// 获取当前月份的日期号码
        this.setEnabled(false);
    }

    /** 是否显示时间对话框 */
    private boolean mshow = true;

    public void showDialog(boolean show) {
        mshow = show;
    }

    /** 只能显示此时间之后的时间 */
    private Date afterDate;

    /** 是否限制最小时间 */
    private boolean hasAfter = false;

    private boolean hasBefore = false;
    private Date beforeDate;

    /**
     * 设置最大日期，只能选择此日期之前的日期
     *
     * @param date
     * @author 鹿云龙
     * @date 2016年1月21日 下午1:21:08
     */
    public void setBefore(Date date) {
        this.beforeDate = date;
        setBefore(true);
    }

    /**
     * 设置是否限制最大日期，默认最大日期为当天
     *
     * @param b
     * @author 鹿云龙
     * @date 2016年1月21日 下午1:21:48
     */
    public void setBefore(boolean b) {
        hasBefore = b;
        if (beforeDate == null && hasBefore) {
            beforeDate = new Date();
        }
    }

    /***
     * 设置只能显示此时间之后的时间,设置后会限制显示之后时间
     *
     * @param date
     * @author 鹿云龙
     * @date 2016年1月20日 下午4:44:38
     */
    public void setAfter(Date date) {
        this.afterDate = date;
        setAfter(true);
    }

    /**
     * 是否限制最小时间,默认最小时间为当天
     *
     * @param setAfter
     *            </br>
     *            true：限制 </br>
     *            false：不限制
     * @author 鹿云龙
     * @date 2016年1月20日 下午4:48:51
     */
    public void setAfter(boolean setAfter) {
        this.hasAfter = setAfter;
        if (afterDate == null && hasAfter) {
            afterDate = GlobalConts.getDate(new Date(), -1);
        }
    }

    public void setAfter(boolean setAfter,int i) {
        this.hasAfter = setAfter;
        if (afterDate == null && hasAfter) {
            afterDate = GlobalConts.getDate(new Date(), i);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
        if (!TextUtils.isEmpty(this.getText())) {
            try {
                String text = this.getText().toString();
                String[] strarr = text.split("-");
                year = Integer.parseInt(strarr[0]);
                month = Integer.parseInt(strarr[1])-1;
                dayOfMonth = Integer.parseInt(strarr[2]);
            } catch (Exception e) {
                e.printStackTrace();
                year = c.get(Calendar.YEAR);
                month = c.get(Calendar.MONTH);
                dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
            }
        } else {
            year = c.get(Calendar.YEAR);
            month = c.get(Calendar.MONTH);
            dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
        }
        if (mshow) {
            if (dateIcon != null && event.getAction() == MotionEvent.ACTION_UP) {
                int eventX = (int) event.getRawX();
                int eventY = (int) event.getRawY();
                Log.e(TAG, "eventX = " + eventX + "; eventY = " + eventY);
                Rect rect = new Rect();
                getGlobalVisibleRect(rect);
                rect.left = rect.right - 81;
                // if (rect.contains(eventX, eventY)) {
                if (datePickerEnabled) {
                    new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {

                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            try {
                                mYear = year;
                                mMonth = monthOfYear;
                                mDay = dayOfMonth;
                                // After(view)) {
                                // view.init(2000, 11, 30, this);
                                // }
                                // if (isDateBefore(v
                                // 从此处判断
                                // /** 是否限制最小时间 */
                                // private boolean hasLater;
                                // /** 只能显示此时间之后的时间 */
                                // private Date laterDate;
                                StringBuilder strb = new StringBuilder().append("").append(mYear).append("-")
                                        .append(mMonth + 1).append("-").append(mDay).append("");
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                Date date = sdf.parse(strb.toString());
                                String dateStr = sdf.format(date);
                                if (hasAfter && hasBefore) {
                                    if (date.after(afterDate) && date.before(beforeDate)) {
                                        setText(dateStr);
                                    }
                                } else if (hasAfter) {
                                    if (date.after(afterDate)) {
                                        setText(dateStr);
                                    } else {
                                        // 提醒用户不能超过此时间
                                        // (Activity)mContext.t
                                        // Activity
                                    }
                                } else if (hasBefore) {
                                    if (date.before(beforeDate)) {
                                        setText(dateStr);

                                    } else {
                                    }
                                } else {
                                    setText(dateStr);
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                    }, year, month, dayOfMonth).show();
                }
            }
        }
        // }
        return super.onTouchEvent(event);
    }

    public boolean isDatePickerEnabled() {
        return datePickerEnabled;
    }

    public void setDatePickerEnabled(boolean datePickerEnabled) {
        this.datePickerEnabled = datePickerEnabled;
        if (!datePickerEnabled) {
            setText("");
        }
    }
}
